package com.example.enterprisemanager.mvvm.fragment.account.login;

import android.app.Application;
import android.arch.lifecycle.MutableLiveData;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.Toast;

import com.example.enterprisemanager.R;
import com.example.enterprisemanager.base.BaseViewModel;
import com.example.enterprisemanager.binding.BindingCommand;
import com.example.enterprisemanager.mvvm.ben.User;
import com.example.enterprisemanager.util.ToastUtil;
import com.orhanobut.logger.Logger;

import io.reactivex.functions.Consumer;

public class LoginViewModel extends BaseViewModel<LoginModel> {
    public ObservableField<String> edtName;
    public ObservableField<String> edtPassword;
    public BindingCommand loginCommand;
    public BindingCommand registerCommand;
    public MutableLiveData<User> sendUser;
    public MutableLiveData<Integer> sendToFrag;

    public LoginViewModel(@NonNull Application application) {
        super(application, new LoginModel());
        init();
    }

    private void init() {
        edtName = new ObservableField<>();
        edtPassword = new ObservableField<>();
        sendUser = new MutableLiveData<>();
        sendToFrag = new MutableLiveData<>();

        loginCommand = new BindingCommand(() -> {
            String name = edtName.get();
            String pass = edtPassword.get();
            Logger.d(name + "\t" + pass);

            if (TextUtils.isEmpty(name)) {
                Toast.makeText(getApplication(), R.string.error_username, Toast.LENGTH_SHORT).show();
                return;
            }
            if (name.length() < 6) {
                Toast.makeText(getApplication(), R.string.str_userName_tip, Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(pass)) {
                Toast.makeText(getApplication(), R.string.error_pwd, Toast.LENGTH_SHORT).show();
                return;
            }
            if (pass.length() < 6) {
                Toast.makeText(getApplication(), R.string.str_pass_tip, Toast.LENGTH_SHORT).show();
                return;
            }

            User user = new User();
            user.setUsername(name);
            user.setPassword(pass);

            mModel.login(user, new Consumer<User>() {
                @Override
                public void accept(User user) throws Exception {
                    sendUser.postValue(user);
                }
            }, new Consumer<Exception>() {
                @Override
                public void accept(Exception e) throws Exception {
                    ToastUtil.show(getApplication(), e.getMessage());
                }
            });
        });
        registerCommand = new BindingCommand(() -> {

            sendToFrag.postValue(1);
        });
    }
}
